#-------------------------------------------------------------------------------
# Name:        Game
# Purpose:
#
# Author:      Theo
#
# Created:     10/02/2012
# Copyright:   (c) Monxcleyr Productions 2012
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, sys, cPickle, zlib, os, logging, random
import config, key, sound, debug, options, common, world, menu, pause, stars, minigame, hud, event, intro, credits
from ..gui import label
from ..tools import videotools
from pygame.locals import *
from . import __version__ #Import engine version


class Game:
  def __init__(self):
    # Class containing common engine variables
    logging.info('Engine Version %s' % __version__)
    self.common = common.Common()
    self.SW = self.common.reswidths[self.common.settings.res_setting] # Load up the defined resolution
    self.SH = int(self.SW / self.common.scale)
    self.size = (self.SW, self.SH)

    # The various surfaces the game will use
    self.menuS = pygame.Surface(self.common.initsize)
    self.menuS.set_colorkey((255,0,255))
    self.optionS = pygame.Surface(self.common.initsize)
    self.optionS.set_colorkey((255,0,255))
    self.gameS = pygame.Surface(self.common.initsize)
    self.gameS.set_colorkey((255,0,255))
    self.mapS = pygame.Surface(self.common.initsize)
    self.titleS = pygame.Surface(self.common.initsize)
    self.fadeS = pygame.Surface(self.common.initsize)
    self.fadeS.fill((0,0,0))
    # Everything is draw onto preS before drawn to the screen
    self.preS = pygame.Surface((self.SW, self.SH))
    # Debug Screen so it can be drawn on top
    self.debugS = pygame.Surface(self.common.initsize, SRCALPHA)
    self.screen = pygame.display.set_mode((self.SW, self.SH), SRCALPHA|DOUBLEBUF)
    if self.common.settings.fullscreen == True:
      self.screen = pygame.display.set_mode(self.size, SRCALPHA|DOUBLEBUF|FULLSCREEN)
    pygame.display.set_caption('#HJ Game Engine Initializing...')
    self.poll = 0
    self.quit = 0
    # Boolean that holds if the size of the display screen has changed
    self.scalechanged = True
    # THis holds if the game is running in either debug mode, set by Main
    self.debugstates = (False, False)
    self.count = 0
    self.mapfollow = False
    # the speed of the physics simulation per step
    self.physicsstep = 90
    self.alpha = 255

    # Modes:
    # 0 = Main Menu
    # 1 = Game
    # 2 = New Game
    # 3 = Load Game
    # 4 = Options Menu
    # 5 = Pause Screen
    # 6 = Developer Console
    # 7 = Updater
    # 8 = Return to previous mode
    # 9 = LOLMINIGAME 1
    # 10 = Intro
    # 11 = Credits
    self.mode = 0
    self.prevmode = 0
    # List of named modes, for debug screen
    self.modes = ['Main Menu', 'Game', 'New Game', 'Load Game', 'Options Menu', 'Pause', 'Console', 'Updater', 'Previous', 'Minigame 1', 'Intro', 'Credits']

    # Create debug class
    self.debug = debug.Debug(False, self.preS, (5,5), (5,5), 4, __version__)

    # MINIGAME CLASS
    self.minigame = minigame.MiniGame(self.common, self.debug)

    # HUD
    self.hud = hud.Hud(self.gameS)

    # LENGTH OF A 'DAY' IN MINUTES:
    self.daylength = 5
    # TIME BETWEEN SCHEDULED TASKS:
    self.taskdelay = 1

    # STARFIELD INIT
    self.starfield = stars.starfield()
    # (255,210,210) redish
    # (210,210,255) blueish
    # (255,255,210) yellowish
    star_sample = [(255,220,220,1),(255,255,255,2),(210,210,255,1),(255,255,220,1),\
      (255,220,220,2),(255,255,255,2),(255,255,255,3),(255,255,255,3),(255,255,255,2), \
      (255,255,255,1),(255,255,255,1),(255,255,255,1),(255,255,255,1),(255,255,255,1), \
      (255,210,210,2),(255,255,255,2),(255,255,255,3),(210,210,255,3),(255,255,255,2), \
      (255,255,210,1),(255,255,210,1),(255,255,255,2),(255,255,255,2),(255,255,255,2),]
    self.starfield.add_layer(50, .25, "down", star_sample, self.common.initsize)
    self.starfield.add_layer(100, .5, "down", star_sample, self.common.initsize)
    self.starfield.add_layer(100, .75, "down", star_sample, self.common.initsize)
    self.starfield.add_layer(100, 1, "down", star_sample, self.common.initsize)
    self.starfield.add_layer(100, 1.25, "down", star_sample, self.common.initsize)


    # event:
    self.eventType = ['radiation','breach','leak','hal 9000']
    self.eventfactory = event.eventFactory()
    self.prevTime = 0
    self.day = 1
    self.canTick = False
    self.currentStation = 'fuck you theo'
    self.fadecount = 0
    self.fadeineffect = True
    self.fadeoutday = False
    self.fadeinday = True
    self.lost = False
    self.bowshock = pygame.image.load('resources/graphics/sprites/bowshock.png')
    self.bowshockpos = (800, 200)

    self.credits = credits.Credits(self.gameS, self.common, self.starfield)

  def newGame(self):
    """ Creates a WHOLE NEW GAME! :O """

    # Create new instance of world class
    self.world = world.World(self.gameS)
    self.minigame = minigame.MiniGame(self.common, self.debug)
    # initiate renderer
##    self.renderer = renderer.Renderer()
##    self.world.loadMap('space', self.screen)
####    self.world.initPymunk(self.screen)
##    self.renderer.load(self.world.currentmap, self.common.initsize)
    logging.info('New game created')


  def postInit(self):
    """ This is a work around method for loading sounds and such after using pygame.movie
    to play the splash screens. """

    self.common.settings.activate()
    self.sound = sound.effect('resources/config/sounds.ini', self.debug)
    self.music = sound.music('resources/config/sounds.ini', self.debug)
    self.menu = menu.Menu(self.menuS, 'menu.ini', self.common, self.sound, self.music, self.debug)
    self.options = options.Options(self.optionS, 'options.ini', self.common, self.sound, self.music, self.debug, self.size)
    # Pause Screen class
    self.pause = pause.Pause('pause.ini', self.common, self.sound, self.music, self.debug)
    self.intro = intro.Intro(self.gameS, self.common, self.music)

  def setMode(self, mode):
    """ Used to change the game's mode.
    Same as using game.mode = x """
    if self.mode != 8:
      if self.prevmode != mode and mode != self.mode:
        self.prevmode = self.mode
    self.mode = mode

  def usePrevMode(self):
    self.mode = self.prevmode
##    self.setMode(self.prevmode)
##    self.setMode(self.prevmode)

  def checkQuit(self):
    if self.quit == 1:
      return True
    else:
      return False

  def updatePreS(self, surface):

    # Draws the game to the main screen
    if surface.get_size() != self.screen.get_size():
      pygame.transform.smoothscale(surface, self.size, self.preS)
    else:
      self.preS.blit(surface, (0,0))

  def saveWorld(self, savename, load=True):
    """ PERMADEATH OR BUST, DO NOT USE THIS EVER """
    self.world.savename = savename
    tempsprites = self.world.imagehandler.sprites
    self.world.imagehandler.reset()
    self.world.removePymunk(self.screen)
    filename = 'Saves'
    f = open(os.path.join(filename, self.world.savename + '.hjsav'), 'wb')
    object1 = zlib.compress(cPickle.dumps(self.world, cPickle.HIGHEST_PROTOCOL),9)
    cPickle.dump(object1,f,cPickle.HIGHEST_PROTOCOL)
    f.close()
    self.world.imagehandler.sprites = tempsprites

    logging.info('Game %s saved', savename)
    if load == True:
      self.loadSave(savename)
##    self.world.loadPhysics(self.screen)
##    self.world.initPymunk(self.screen)

  def loadSave(self, savename):
    """ LOAD A SAVE LOLOL """
    filename = 'Saves'
    try:
      f = open(os.path.join(filename, savename + '.hjsav'),'rb')
      obj = cPickle.load(f)
      self.world = cPickle.loads(zlib.decompress(obj))
      f.close()
    except IOError as e:
      logging.critical('Failed to load save %s' % savename)

    # This makes the world reload the map, instead of using the one in memory, in case map
    # files were updated
    self.world.loadMap(self.world.currentmapname, self.screen)
    # Let the render load up the correct map
##    self.world.initPymunk(self.screen)
    self.renderer = renderer.Renderer()
    self.renderer.load(self.world.currentmap, self.common.initsize)
    self.world.createCollisionBodies(self.screen)
    # Reset camera pos to previous position
    self.renderer.moveCamera(self.world.camerapos)
    logging.info('Game %s loaded', savename)


  def changeMap(self, mapname, savename):
    """ Change map being used by the world and renderer"""
    self.saveWorld(savename, load=False)
    self.world.removePymunk(self.screen)
    self.world.loadMap(mapname, self.screen)
    self.world.camerapos = (0,0)
##    self.world.initPymunk(self.screen)
    self.renderer.load(self.world.currentmap, self.common.initsize)
    self.world.createCollisionBodies(self.screen)
    logging.info('Changed map to %s', mapname)

  def randomEvent(self, imagehandler, rectsize, active,startTime, endTime):
    self.randCoord = [(234,123),(123,253),(123,456)]
    rint = random.randint(1,3)
    if rint == 1:
      self.world.stations.addLeakEntity(self.randCoord[random.randint(0,2)], 'leak.png', imagehandler, rectsize, 'leak', True)
      self.world.stations.addLeakEntity(self.randCoord[random.randint(0,2)], 'leak.png', imagehandler, rectsize, 'leak', True)
      self.world.stations.addLeakEntity(self.randCoord[random.randint(0,2)], 'leak.png', imagehandler, rectsize, 'leak', True)
      self.eventfactory.add_event('leak',endTime,"inactive",startTime)
    elif rint == 2:
      self.world.stations.addBreachEntity(self.randCoord[random.randint(0,2)], 'breach.png', imagehandler, rectsize, 'breach', True)
      self.world.stations.addBreachEntity(self.randCoord[random.randint(0,2)], 'breach.png', imagehandler, rectsize, 'breach', True)
      self.world.stations.addBreachEntity(self.randCoord[random.randint(0,2)], 'breach.png', imagehandler, rectsize, 'breach', True)
      self.eventfactory.add_event('breach',endTime,"inactive",startTime)
    elif rint == 3:
      self.world.stations.addAIPanelEntity((500,300), 'aipanel.png', imagehandler, rectsize, 'ai panel', True)
      self.eventfactory.add_event('hal 9000',endTime,"inactive",startTime)


#-------------------------------------------------------------------------------
#--------------------------------- Game Loop -----------------------------------
#-------------------------------------------------------------------------------


  def runGame(self, time, keyPressed):

    # FUCK YOU, THEO
    if 'theo' == 'theo':
      fuckyou = True

    self.common.time = time
    self.limit = 100
    elpTime = (int(round(self.world.runningtime/1000)) % self.limit) + 1
    timeLeft =  self.limit - elpTime
    self.gameS.fill((0,0,0))


    if timeLeft == 0:
      self.world.runningtime += 1000
      self.day += 1

##    print elpTime, self.world.runningtime
    if self.day == 1:

      if elpTime == 2:
        self.hud.setText(["Day 9", \
          "A little over a week since I separated from the hub. For a solo mission like this they put you on the multi-stations ", \
          "until you're within a close enough distance that the isolation is considered to be of a responsible length. I'm not ", \
          "sure why I'm writing this now, only to say that it's already felt like a hell of a long time.", \
           "There are two things I would change - Gliese 581d. My destination. The planet itself is fine; it's a far more interesting", \
           "EE assignment than most will get. The robotic reconnaissance missions to the planet over the past decade confirmed", \
           "it had oceans. That was a bigger deal a few decades ago, but it's still exciting - most of us will land on dry rocks ", \
           "that are simply lucky enough, depending on how you look at it, to be situated in a narrow band of habitability.", \
           "People in my position will never see that part of it. But, the name. Gliese 581d. The way they announce these missions,", \
           "you expect a little more - a certain romance to the name. A new world. It's difficult in the video coms I make every ", \
           "night to talk as if it's a territory worth setting out for. It could have a better name.", \
           " ", \
           "Oh, and the second thing: More windows. I'd put in more windows.", \
           " ", \
           " ",])
        self.world.runningtime += 1000
        self.canTick = False


      if elpTime == 15:
        #TEXT: Go to the life support and do life support stuff or whatever
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Rachel Miller,", \
        "Life support systems in the port module are ready for routine evaluation. There are no reported inconsistencies.", \
        " ", \
        "(Use the WASD keys to move around the spaceship. Walk over and onto the specified station and press the 'E'", \
        "key to interact with it.)", \
        " ", \
        " ", \
        "(In order to evaluate or fix a station, you will have to connect a set of colored circuits, taking up every available", \
        "spot without crossing paths. To do this, select one of the colors from the top selection bar, and click on one of the ", \
        "squares to fill in that color. Press the 'Reset' button if you need to restart.)"])
        self.world.runningtime += 1000

      if elpTime == 17:
        self.canTick = False
        self.currentStation = 'life support'
        self.world.runningtime += 1000

      if elpTime == 19:
        self.hud.setText(["Commander Miller:",\
        "Still working fine. Having me check this every day is making me worry.", \
        " ", \
        " ", \
        "On-board artificial inteligence:", \
        "It is standard protocol to evaluate each system."])
        self.world.runningtime += 1000

      if elpTime == 30:
        #TEXT: Get some food, you dummy
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "It is recommended that you visit the health station and food depository in the starboard wing at this time.",\
        " ", \
        "Commander Miller:",\
        "It's a glorified alarm clock."])
        self.world.runningtime += 1000

      if elpTime == 32:
        self.canTick = False
        self.currentStation = 'health'
        self.world.runningtime += 1000

      if elpTime == 45:
        #TEXT: Navigate somewhere over there or something
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "The computer systems and A.I. nodes in the center module are primed for routine examination and maintenance."])
        self.world.runningtime += 1000

      if elpTime == 47:
        self.canTick = False
        self.currentStation = 'ai'
        self.world.runningtime += 1000

      if elpTime == 49:
        self.hud.setText(["Commander Miller:", \
        "Everything checks out."])
        self.world.runningtime += 1000

      if elpTime == 60:
        #TEXT: check power
        self.hud.setText(["Commander Miller:", \
        "Being an ocean planet, it will likely be flagged for research purposes. Depending on how that process goes, ", \
        "industrial might move in. I hope to enjoy the six months I have before they arrive. You expect, like the saying goes,",\
        "to enjoy the journey more than the destination. But it's strange knowing exactly where you're going to be.",\
        "On-board artificial intelligence:",\
        "The electrical system powering the craft located on the starboard side of the forward module is in need of a short", \
        "review and evaluation"])
        self.world.runningtime += 1000

      if elpTime == 62:
        self.canTick = False
        self.currentStation = 'power'
        self.world.runningtime += 1000

      if elpTime == 64:
        self.hud.setText(["Commander Miller:", \
        "Checks out. It'll be awhile before we have to replace anything in here."])
        self.world.runningtime += 1000


      if elpTime == 80:
        #TEXT: RANDOM EVENT
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. A breach of the exterior hull has been identified.",\
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. Immediate attention is required.",\
        "(During emergency events, the process of connecting circuits becomes more difficult and must be done within a time", \
        "limit. This timer is displayed at the top of the screen.)"])
        self.world.runningtime += 1000

      if elpTime == 82:
        for station in self.world.stations.stationList:
          if station.type == 'breach1':
            station.active = True
        self.canTick = False
        self.currentStation = 'breach1'
        self.world.runningtime += 1000

      if elpTime == 84:
        self.hud.setText(["Commander Miller:",\
        "All clear, this was a minor breach. I'm assuming this is the first of many, so the slow start was welcome."])
        self.world.runningtime += 1000

      if elpTime == 97:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "It is recommended that you retire to your living quarters at this time for mandatory rest and optional relaxation."])
        self.world.runningtime += 1000

      if elpTime == 99:
        self.fadeoutday = True
        self.world.runningtime += 1000
        self.canTick = True

    elif self.day == 2:

      if elpTime == 13:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "Life support systems in the appropriate module are ready for routine evaluation. There are no reported inconsistencies."])
        self.world.runningtime += 1000

      if elpTime == 15:
        #TEXT: Go to the life support and do life support stuff or whatever
        self.canTick = False
        self.currentStation = 'life support'
        self.world.runningtime += 1000

      if elpTime == 28:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "It is recommended that you visit the health station and food depository in the starboard wing at this time."])
        self.world.runningtime += 1000

      if elpTime == 30:
        #TEXT: Get some food, you dummy
        self.canTick = False
        self.currentStation = 'health'
        self.world.runningtime += 1000

      if elpTime == 40:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. A volatile fluid leak has been detected in the ship's interior.",\
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. Immediate attention is required."])
        self.world.runningtime += 1000

      if elpTime == 42:
        for station in self.world.stations.stationList:
          if station.type == 'leak1':
            station.active = True
        self.canTick = False
        self.currentStation = 'leak1'
        self.world.runningtime += 1000

      if elpTime == 50:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "The computer systems and A.I. nodes in the center module are primed for routine examination and maintenance."])
        self.world.runningtime += 1000

      if elpTime == 52:
        self.canTick = False
        self.currentStation = 'ai'
        self.world.runningtime += 1000

      if elpTime == 54:
        self.hud.setText(["Commander Miller:", \
        "You're still looking good."])
        self.world.runningtime += 1000

      if elpTime == 69:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. A breach of the exterior hull has been identified.",\
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. Immediate attention is required."])
        self.world.runningtime += 1000

      if elpTime == 71:
        for station in self.world.stations.stationList:
          if station.type == 'breach2':
            station.active = True
        self.canTick = False
        self.currentStation = 'breach2'
        self.world.runningtime += 1000

      if elpTime == 85:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "Current flight path and other navigational systems require review and approval. No corrections are presently",\
        "scheduled."])
        self.world.runningtime += 1000

      if elpTime == 87:
        self.canTick = False
        self.currentStation = 'navigation'
        self.world.runningtime += 1000

      if elpTime == 89:
        self.hud.setText(["Commander Miller",\
        "No course corrections today. The time-table for these flights is thought of as being immutable, but with the", \
        "adjustments we've already had to make the original date won't be near the reality. That is to say while I don't",\
        "count down the days, I know when we'll arrive."])
        self.world.runningtime += 1000

      if elpTime == 97:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "It is recommended that you retire to your living quarters at this time for mandatory rest and optional relaxation.",\
        " ",\
        "Commander Miller:",\
        "I'll let you know when I take that option."])
        self.world.runningtime += 1000

      if elpTime == 99:
        self.fadeoutday = True
        self.world.runningtime += 1000
        self.canTick = True


    elif self.day == 3:

      if elpTime == 13:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "Life support systems in the appropriate module are ready for routine evaluation. There are no reported inconsistencies."])
        self.world.runningtime += 1000

      if elpTime == 15:
        self.canTick = False
        self.currentStation = 'life support'
        self.world.runningtime += 1000

      if elpTime == 20:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. A volatile fluid leak has been detected in the ship's interior.",\
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. Immediate attention is required."])
        self.world.runningtime += 1000

      if elpTime == 22:
        for station in self.world.stations.stationList:
          if station.type == 'leak1':
            station.active = True
        self.canTick = False
        self.currentStation = 'leak1'
        self.world.runningtime += 1000

      if elpTime == 28:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "It is recommended that you visit the health station and food depository in the starboard wing at this time."])
        self.world.runningtime += 1000

      if elpTime == 30:
        #TEXT: Get some food, you dummy
        self.canTick = False
        self.currentStation = 'health'
        self.world.runningtime += 1000

      if elpTime == 43:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "The computer systems and A.I. nodes in the center module are primed for routine examination and maintenance."])
        self.world.runningtime += 1000

      if elpTime == 45:
        self.canTick = False
        self.currentStation = 'ai'
        self.world.runningtime += 1000

      if elpTime == 58:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "The electrical system powering the craft located on the starboard side of the forward module is in need of a short",\
        "evaluation and repair. Diagnostics suggest a replacement of the first set of power nodes."])
        self.world.runningtime += 1000

      if elpTime == 60:
        self.canTick = False
        self.currentStation = 'power'
        self.world.runningtime += 1000

      if elpTime == 66:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. A breach of the exterior hull has been identified.",\
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. Immediate attention is required."])
        self.world.runningtime += 1000

      if elpTime == 68:
        for station in self.world.stations.stationList:
          if station.type == 'breach2':
            station.active = True
        self.canTick = False
        self.currentStation = 'breach2'
        self.world.runningtime += 1000

      if elpTime == 80:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. A breach of the exterior hull has been identified.",\
        "THIS IS AN EMERGENCY DISTRESS SIGNAL. Immediate attention is required.",\
        "Commander Miller:",\
        "Did you hit something!?", \
        " ",\
        " ",\
        "On-Board artificial intelligence:",\
        "Sensors and diagnostic readings suggest the ship is passing through the tail of a nearby comet.",\
        " ",\
        " ",\
        "Commander Miller:",\
        "Just keep it steady and hold on. We don't have much farther."])
        self.world.runningtime += 1000

      if elpTime == 82:
        #TEXT: RANDOM EVENT
        for station in self.world.stations.stationList:
          if station.type == 'breach1':
            station.active = True
        self.canTick = False
        self.currentStation = 'breach1'
        self.world.runningtime += 1000

      if elpTime == 88:
        self.canTick = False
        self.currentStation = 'power'
        self.world.runningtime += 1000

      if elpTime == 90:
        self.hud.setText(["Commander Miller:",\
        "Of course this would be a busy day. Stick with me a bit longer, will you?"])
        self.world.runningtime += 1000

      if elpTime == 96:
        self.hud.setText(["On-board artificial intelligence:", \
        "Commander Miller,", \
        "Brief announcement: Navigational systems indicate that this craft is approaching Gliese 581d. Destination can now",\
        "be viewed through the forward window. Immediate preparation on all systems required for approach and descent.",\
        'Commander Miller:',\
        "Look at it, suspended there, and us traveling to it on a tightrope. Locking in the flight path, communicating with the",\
        "systems already in orbit - I'll get to it. We're not far - and it's blue, but not exactly.",\
        " ",\
        "Tell me what's next."])
        self.world.runningtime += 1000

      if elpTime == 98:
        self.mode = 11


##      if elpTime == self.limit:
##        self.mode = 11
##        #THE END CATWOMAN BEGINS


    # Controls music queue
    if self.music.getCurrentLoop() != 'ambience':
      self.music.loadQueue('ambience')
      self.music.playQueue()
    if pygame.mixer.music.get_busy() == 0:
      self.music.playQueue()

#-------------------------------------------------------------------------------

    key = pygame.key.get_pressed()
##
##    # Bring up puase screen
##    if self.pause.gamecount > 10:
##      if key[self.common.key.bind['pause']]:
##        self.setMode(5)
##    self.pause.gamecount += 1

#-------------------------------------------------------------------------------


    # Temporary function key stuff
    if key[pygame.K_F1]:
      self.minigame.load('hard', 300)
      self.mode = 9



    self.world.updateCollisions()

    # DRAW STARFIELD
    self.starfield.draw(self.gameS)

    # DRAW SHIP
    self.gameS.blit(self.world.imagehandler.getSprite('ship.bmp'), self.world.shippos)

    self.world.stations.draw(self.gameS)

    # Draw Player
    self.world.player.draw(self.gameS)


    if self.minigame.passed == True:
      self.minigame.passed = None
      self.canTick = True

      if self.currentStation == 'breach1':
        # WOOOOOO
        print 'HULL BREACH REPAIRED'
        for station in self.world.stations.stationList:
          if station.type == 'breach1':
            station.active = False
      if self.currentStation == 'breach2':
        # WOOOOOO
        print 'HULL BREACH REPAIRED'
        for station in self.world.stations.stationList:
          if station.type == 'breach2':
            station.active = False
      if self.currentStation == 'leak1':
        # WOOOOOO
        print 'FLUID LEAK FIXED'
        for station in self.world.stations.stationList:
          if station.type == 'leak1':
            station.active = False


      self.currentStation = 'fuck you theo'

    if self.minigame.passed == False:
      if self.lost == False:
        self.hud.setText(["On-board artificial intelligence:", \
        "Explore and Evaluate-1 mission to Gliese-581d failed. Replacement candidates under review."])
        self.lost = True

    if self.lost and self.canTick:
      self.mode = 11



##    print self.minigame.passed, self.currentStation
    tempstation = self.world.player.checkInRange(self.world.stations.stationList)
    if tempstation:
      if tempstation.type == self.currentStation:
        if self.currentStation == 'breach1':
          self.minigame.load('hard', 30)
          self.mode = 9
        elif self.currentStation == 'leak1':
          self.minigame.load('hard', 30)
          self.mode = 9
        elif self.currentStation == 'breach2':
          self.minigame.load('hard', 30)
          self.mode = 9
        else:
          self.minigame.load('easy')
          self.mode = 9

    self.bowshockpos = (self.bowshockpos[0], self.bowshockpos[1] +.5)
    if self.bowshockpos[1] > 600:
      pass
    else:
      self.gameS.blit(self.bowshock, self.bowshockpos)


    # Draw Hud
    if self.hud.drawnow:
      self.canTick = self.hud.draw(self.canTick, keyPressed)
    else:

      if key[self.common.key.bind['up']]:
        self.world.player.move((0,-.75))
      if key[self.common.key.bind['down']]:
        self.world.player.move((0,.75))
      if key[self.common.key.bind['left']]:
        self.world.player.move((-.75,0))
      if key[self.common.key.bind['right']]:
        self.world.player.move((.75,0))

##
    # fade in

    if self.fadeineffect:
      temp = self.fadeIn((255,255,255))
      if temp:
        self.fadeineffect = False
        self.world.runningtime += 1000

    # Day switching
    if self.fadeoutday == True:
      temp = self.fadeOut()
      if temp:
        self.fadeoutday = False
        self.fadeinday = True
        self.world.player.worldpos = self.world.playerspawn

    if self.fadeinday == True:
      temp = self.fadeIn((0,0,0))
      if temp:
        self.fadeinday = False

    if self.canTick:
      self.world.runningtime += time


  def fadeIn(self, color):
    self.fadeS.fill(color)

    self.fadeS.set_alpha(self.alpha)
    self.gameS.blit(self.fadeS, (0,0))
    self.alpha -= 2.55
    if self.alpha <= 0:
      return True


  def fadeOut(self):
    self.fadeS.fill((0,0,0))
    self.alpha += 2.55
    self.fadeS.set_alpha(self.alpha)
    self.gameS.blit(self.fadeS, (0,0))

    if self.alpha >= 255:
      return True




